package com.task.scheduling.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: task-scheduling
 * @description: 存放线程执行的future
 * @author: zhouliangliang
 * @create: 2019-03-08 19:56
 **/
public class FutureHolder {

    private static Logger log = LoggerFactory.getLogger(FutureHolder.class);

    private static Lock lock = new ReentrantLock();

    private static Map<Long, Future<?>> map = new HashMap<>();

    private FutureHolder() {

    }

    public static void holdFuture(Long id, Future<?> future) {
        try {
            lock.lock();

            if(map.get(id) != null) {
                log.info("任务{}的执行线程已经在记录中", id);
            } else {
                map.putIfAbsent(id, future);
                log.info("任务{}的执行线程持有成功", id);
            }
        } catch (Exception e) {
            log.error("hold future error!" + e.getMessage(), e);
        } finally {
            lock.unlock();
        }
    }

    public static void removeFuture(Long id) {
        try {
            lock.lock();
            map.remove(id);
            log.info("任务{}的执行线程释放成功", id);
        } catch (Exception e) {
            log.error("remove future error!" + e.getMessage(), e);
        } finally {
            lock.unlock();
        }
    }

    public static Future<?> getFuture(Long id) {
        try {
            lock.lock();
            return map.get(id);
        } catch (Exception e) {
            log.error("get future error!" + e.getMessage(), e);
            return null;
        } finally {
            lock.unlock();
        }
    }

    public static Map<Long, Future<?>> getRunningThreadMap(){
        return map;
    }
}
